package com.wkg.springblogdemo.common.advice;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wkg.springblogdemo.common.exception.BlogException;
import com.wkg.springblogdemo.pojo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
    /*@ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("发生异常: ", e);  // 确保此处打印e的完整堆栈
        return Result.fail(e.getMessage());
    }*/


    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("发生异常: ", e);  // 关键：将异常对象e作为最后一个参数
        return Result.fail("操作失败");
    }

    @ExceptionHandler
    public Result exceptionHandler(BlogException e) {
        log.error("发生异常, e: ", e.getMessage());
        return Result.fail(e.getErrMsg());
    }

    @ExceptionHandler
    public Result exceptionHandler(HandlerMethodValidationException e) {
        log.error("发生异常, e: ", e.getMessage());
        List<String> errors = new ArrayList<>();
        e.getAllErrors().forEach(error -> errors.add(error.getDefaultMessage()));
        return Result.fail("参数校验失败");
    }


    @ExceptionHandler
    public Result verifyHandle(MethodArgumentNotValidException e) {
        log.error("发生异常: {}", e.getMessage());
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();

        return Result.fail(defaultMessage);
    }






}
